package com.cdp.web.controller.system;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cdp.common.core.controller.BaseController;
import com.cdp.common.core.domain.AjaxResult;
import com.cdp.common.core.domain.entity.SysUser;
import com.cdp.common.utils.SecurityUtils;
import com.cdp.framework.web.service.SysRegisterService;
import com.cdp.system.service.ISysConfigService;
import com.cdp.system.service.ISysUserService;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
/**
 * 注册验证
 *
 * @author ruoyi
 */
@Slf4j
@Api(value = "用户", tags = {"User Operations"})
@RestController
@RequestMapping()
public class SysRegisterController extends BaseController {
    //全球手机号正则表达式
    private static final String PHONE_NUMBER_REGEX = "^(?:\\+?(\\d{1,3}))?[-. (]*(\\d{1,4})?[-. )]*(\\d{1,4})?[-. ]*(\\d{1,4})?[-. ]*(\\d{1,9})?$";

    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/registers")
    public AjaxResult register(@RequestBody SysUser user) {
        //@Validated 如果 User 对象中有不符合规则的字段，Spring 会自动抛出异常
        // 手机号码格式验证
        String phonenumber = user.getPhonenumber();
        if (!phonenumber.matches(PHONE_NUMBER_REGEX)) {
            log.error("手机号：{}格式不正确", phonenumber);
            return AjaxResult.error("手机号码格式不正确");
        }
        //用户数据验证
        if (ObjectUtils.isNotEmpty(user.getPhonenumber())) {
            //查询之前检查数据的一致性
            long count = userService.count(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getPhonenumber, user.getPhonenumber()));
            if (count > 1) {
                log.error("在数据库中找到了多条手机号：{}", user.getPhonenumber());
                throw new IllegalStateException("手机号码不唯一，找到了多条记录");
            }

            SysUser sysUser = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, user.getPhonenumber()));
            if (ObjectUtils.isNotEmpty(sysUser)) {
                log.info("用户：{}手机号码：{}已存在", sysUser, user.getPhonenumber());
                return AjaxResult.error("用户'" + user.getPhonenumber() + "'注册失败，手机号码已存在");
            }
        }
        user.setNickName(user.getPhonenumber());
        user.setUserName(user.getPhonenumber());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        try {
            boolean b = userService.insertUser(user);
            if (b) {
                log.info("用户：{}注册成功", user.getPhonenumber());
                return AjaxResult.success();
            } else {
                log.warn("用户：{}注册失败，未知原因", user.getPhonenumber());
                throw new RuntimeException("用户注册失败，未知原因");
            }
        } catch (Exception e) {
            log.error("用户：{}注册失败：{}", user.getPhonenumber(), e.getMessage());
            throw new RuntimeException(e);
        }


    }



    @PostMapping("/query/userList")
    public AjaxResult queryUserList(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        // 参数校验
        if (pageNum == null || pageSize == null) {
            return AjaxResult.error("分页参数不能为空");
        }

        System.out.println("pageNum: " + pageNum + ", pageSize: " + pageSize);

        try {
            PageHelper.startPage(pageNum, pageSize);
            List<SysUser> sysUsers = userService.list();
            log.info("查询用户列表成功sysUsers={}",sysUsers);
            return AjaxResult.success(sysUsers);
        } catch (Exception e) {
            e.printStackTrace(); // 输出异常栈
            return AjaxResult.error("查询用户列表失败: " + e.getMessage());
        }
    }




}
